<template>
  <div class="search" :style="{ '--themeColor': themeColor }">
    <nav-bar title="门店列表" />
    <div class="head">
      <div class="input">
        <u-search
          shape="round"
          :focus="isFocus"
          bgColor="#fff"
          clearabled
          v-model="queryParams.shopName"
          searchIconSize="26"
          maxlength="10"
          @search="searchShop"
          @custom="searchShop"
          @focus="showHistory = true"
          placeholder="请输入搜索内容"
        />
      </div>
      <multistep-filter
        v-if="!showHistory"
        :filterItems="filterItems"
        @changeSelect="changeSelect"
        ref="initSelectArr"
        :defaultList="defaultList"
      />
    </div>
    <div class="histoy" v-if="showHistory">
      <div class="top">
        <div class="title">历史搜索</div>
        <u-icon
          name="trash"
          color="#888888"
          size="24"
          @click="clearHistory"
        ></u-icon>
      </div>
      <div class="list">
        <div
          class="one"
          v-for="item in historyList"
          :key="item"
          @click="setSearch(item)"
        >
          {{ item }}
        </div>
      </div>
    </div>
    <div class="shop-list" v-show="showHistory == false">
      <mescroll-uni
        :fixed="false"
        ref="mescrollRef"
        @down="downCallback"
        @up="upCallback"
        :up="{
          auto: false,
          textNoMore: '没有更多了',
          empty: {
            tip: '暂无相关数据',
            icon: 'https://hyyxboss.oss-cn-shenzhen.aliyuncs.com//img/pub/no_data.png',
            fixed: true,
            top: '40%',
          },
        }"
        :down="{
          auto: false,
        }"
      >
        <div
          v-for="(item, index) in dataList"
          :key="item.id"
          class="shop-content"
          @click="$myTool.jumpPage('shopIndex', { shopId: item.id })"
        >
          <div class="img">
            <xh-img :src="item.logo" />
          </div>
          <div class="msg">
            <div class="top">
              <div class="title">{{ item.name }}</div>
              <div class="detail">
                <div class="left">
                  <div :class="['falg', item.isOpen ? 'open' : '']">
                    {{ item.isOpen ? "营业中" : "休息中" }}
                  </div>
                  <div class="type">{{ industryType[item.industry] }}</div>
                  <div class="month">月售{{ item.monthSales }}</div>
                </div>
                <div class="distance" v-if="item.distance">
                  {{ $myTool.transitionDistance(item.distance) }}
                </div>
              </div>
            </div>

            <div class="store-val">
              <text v-if="item.balanceActivityDesc" class="balanceActivityDesc" style="margin-right: 10rpx">
                {{ item.balanceActivityDesc }}
              </text>
              <!-- <text
                v-for="(config, configIndex) in item.shopConfig"
                :key="configIndex"
                style="margin-right: 10rpx"
                >{{ config.label }}</text
              > -->
            </div>
          </div>
        </div>
      </mescroll-uni>
    </div>
  </div>
</template>

<script>
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
import multistepFilter from "@/components/pageComponents/sp-store/multistepFilter";
import { getShops } from "@/service/api/sp-store/index";
import { mapState } from "vuex";
export default {
  mixins: [MescrollMixin], // 使用mixin
  data() {
    return {
      historyList: [],
      goodsHistory: {},
      showHistory: true,
      isFocus: true,
      dataList: [],
      queryParams: {
        latitude: "",
        longitude: "",
        shopName: "",
        // 门店类型 1餐饮；2便利店；3休闲娱乐；4美容美发， 不传则查全部类型
        shopType: "",
        industry: "",
        // 排序规则 1综合排序 2距离优先 3人气优先
        sortType: 1,
        pageNum: 1,
        pageSize: 10,
      },
      filterItems: [
        [{}],
        [
          {
            label: "综合排序",
            value: "1",
          },
          {
            label: "距离优先",
            value: "2",
          },
          {
            label: "人气优先",
            value: "3",
          },
        ],
      ],
      defaultList: [],
    };
  },
  computed: {
    ...mapState("sp-common/base", ["themeColor"]),
    ...mapState("sp-store/index", ["industryType"]),
  },
  watch: {
    industryType: {
      handler(value) {
        let selectArr = [];
        Object.keys(value).forEach((item) => {
          let obj = {
            label: value[item] || 0,
            value: item,
          };
          selectArr.push(obj);
        });
        this.filterItems[0] = selectArr;
      },
      deep: true,
    },
  },
  components: {
    multistepFilter,
  },
  onReady() {
    if (this?.$Route?.query?.industryType) {
      this.queryParams.industry = this?.$Route?.query?.industryType;
      this.defaultList = [this?.$Route?.query?.industryType];
      this.showHistory = false;
      this.isFocus = false;
    }
    this.getUserLocation();
    this.getHistory();
  },
  onUnload() {
    this.setHistory();
  },
  methods: {
    searchShop() {
      let {
        historyList,
        queryParams: { shopName },
      } = this;
      if (!shopName) return;
      if (historyList.indexOf(shopName) !== -1) {
        historyList.splice(historyList.indexOf(shopName), 1);
      }
      this.historyList.unshift(shopName);
      if (historyList.length === 9) this.historyList.pop();
      this.showHistory = false;
      this.mescroll.resetUpScroll();
    },
    getHistory() {
      let selectArr = [],
        value = this.industryType;

      uni.getStorage({
        key: "goodsHistory",
        success: (res) => {
          this.goodsHistory = JSON.parse(res.data);
          this.historyList = this.goodsHistory || [];
        },
      });
      Object.keys(value).forEach((item) => {
        let obj = {
          label: value[item] || 0,
          value: item,
        };
        selectArr.push(obj);
      });
      this.filterItems[0] = selectArr;
    },
    setHistory() {
      let { historyList } = this;
      uni.setStorage({
        key: "goodsHistory",
        data: JSON.stringify(historyList),
      });
    },
    clearHistory() {
      this.historyList = [];
    },
    setSearch(item) {
      this.queryParams.shopName = item;
      this.searchShop();
    },
    changeSelect(val) {
      this.queryParams.industry = val.key1;
      this.queryParams.sortType = val.key2;
      this.mescroll.resetUpScroll();
    },
    fetData() {
      let {
        queryParams,
        queryParams: { pageNum },
      } = this;
      getShops(queryParams)
        .then((res) => {
          let { total, list = [] } = res;
          if (!list) list = [];
          list.map((l) => {
            const shopConfig = [
              {
                prop: "freeWifi",
                label: "免费WiFi",
                value: false,
              },
              {
                prop: "isShopConsume",
                label: "到店消费",
                value: false,
              },
              {
                prop: "isSelfPack",
                label: "自提",
                value: false,
              },
              {
                prop: "packFee",
                label: "打包",
                value: false,
              },
              {
                prop: "isDelivery",
                label: "外卖配送",
                value: false,
              },
              {
                prop: "isEatShop",
                label: "堂食",
                value: false,
              },
            ];
            shopConfig.map((config) => {
              if (!!l?.shopConfigJson[config.prop]) {
                config.value = true;
              }
            });
            l.shopConfig = shopConfig.filter((config) => !!config.value);
          });
          if (pageNum === 1) this.dataList = [];
          this.mescroll.endBySize(list.length || 0, total);
          this.dataList =
            pageNum === 1 ? list || [] : this.dataList.concat(list);
          this.showHistory = false;
        })
        .catch(() => {
          this.mescroll.endErr();
          this.showHistory = false;
        });
    },
    downCallback(page) {
      this.queryParams.pageNum = 1;
      this.mescroll.resetUpScroll();
    },
    upCallback(page) {
      this.queryParams.pageNum = page.num;
      this.fetData();
    },
    getUserLocation() {
      let {
        queryParams: { longitude, latitude },
      } = this;
      if (!longitude || !latitude) {
        this.$getUserLocation()
          .then((res) => {
            let result = res?.currentLocation
              ? res?.currentLocation
              : res?.location;
            let { longitude, latitude } = result;
            this.queryParams = Object.assign({}, this.queryParams, {
              longitude,
              latitude,
            });
            if (this.queryParams.industry || this.defaultList.length > 0) {
              this.mescroll.resetUpScroll();
            }
          })
          .catch(() => {
            this.mescroll.endErr();
          });
        return;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/pages/sp-store/css/shop-search.scss";
</style>
